package com.itheima.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Employee findOne(Employee employee) {
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        String passwordMd5 = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        lqw.eq(Employee::getUsername, employee.getUsername()).eq(Employee::getPassword, passwordMd5);
        return employeeMapper.selectOne(lqw);
    }

    @Override
    public Page<Employee> findEmployeePage(int page, int pageSize, String name) {
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //lqw.like(name != null && !name.trim().equals(""), Employee::getName, name);
        lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //按更新时间降序排序
        lqw.orderByDesc(Employee::getUpdateTime);
        employeeMapper.selectPage(pageInfo, lqw);

        return pageInfo;
    }

    @Override
    public void updateById(Employee employee) {
        //设置更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //获取当前登录用户的id
        //Long id = (Long) request.getSession().getAttribute("employee");
        //设置更新员工信息的用户的id
        //employee.setUpdateUser(id);
        employeeMapper.updateById(employee);
    }

    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        return employee;
    }

    @Override
    public void save(Employee employee) {
        //设置初始密码123456,用MD5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置跟新和创建时间
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        //获取当前登录用户的id
        //Long id = (Long) request.getSession().getAttribute("employee");
        //设置创建员工信息的用户的id
        //employee.setCreateUser(id);
        //设置更新员工信息的用户的id
        //employee.setUpdateUser(id);
        employeeMapper.insert(employee);
    }
}

